//待补充
$NG.AllReady(function (
    editPage,
    { useAction, useValuesChange, useUpdateRow, useDataIndexChange, useUpdateRows, useClick }
) {
    const mstform = $NG.getCmpApi("p_form_dev_cost_budget_chg")
	const dgrid1 = $NG.getCmpApi("p_form_dev_labor_budget_chg")
	const dgrid2 = $NG.getCmpApi("p_form_dev_daliy_budget_chg")
    cntMFilter()
    useValuesChange(({args})=>{
        console.log(`监听项目选择变化`, args);
        getPtInfoByPhid()
        cntMFilter()
    }, "p_form_dev_cost_budget_chg.phid_pc")

    // 监听合同变化
    useValuesChange(({args})=>{
        getCntInfo()
    }, "p_form_dev_cost_budget_chg.u_cnt")
    useUpdateRows(({args})=>{
        sum()
    }, "p_form_dev_labor_budget_chg")
    useUpdateRows(({args})=>{
        sum()
    }, "p_form_dev_daliy_budget_chg")

	useValuesChange(({ args }) => {
		console.log(args[0]);
		getCntInfo()
		dgrid1.clearRows();
		dgrid2.clearRows();
		setTimeout(() => {
			// 赋值
			function _sum(num) {
				$NG.updateState((updater) => {
					updater.data.p_form_dev_cost_budget_chg.setProps({
						u_total_dev_amt_ori: num
					})
				})
			}
			// 临时存储上一次的费用
			const _countMaps = {
				_d1: 0,
				_d2: 0,
				_d3: 0,
				set d1(value) {
					this._d1 = value
					_sum(this._d1 + this._d2 + this._d3)
				},
				set d2(value) {
					this._d2 = value
					_sum(this._d1 + this._d2 + this._d3)
				},
				set d3(value) {
					this._d3 = value
					_sum(this._d1 + this._d2 + this._d3)
				},
			}
			Object.defineProperties(_countMaps, {
				_d1: {
					configurable: false,
					writable: true,
					enumerable: false,
					value: 0
				},
				_d2: {
					configurable: false,
					writable: true,
					enumerable: false,
					value: 0
				},
				_d3: {
					configurable: false,
					writable: true,
					enumerable: false,
					value: 0
				},
			})
			if (dgrid1) {
				$NG.execServer('getDevLaborBudgetInfo', {
					cnt: mstform.getItem('u_cnt').getValue()
				}, function (res) {
	
					let _data = null
					if (typeof res.data === 'string') {
						_data = JSON.parse(res.data)
					} else {
						_data = res.data
					}
					console.log(`人工明细`, _data,res);
					//默认增行,批量新增表体数据
					var gridArr = []; //定义表体数组
					var gridCount = res.count; //增加的行数,可根据从数据库从取出的数据总数增行
					for (var i = 0; i < gridCount; i++) {
						var gridObj = {
						};
						//对表体字段进行赋值,可以取数据库中的值进行赋值
						// 来源主键
						gridObj.u_source_phid = _data[i].extendObjects.phid
						// 年度
						gridObj.u_year = _data[i].extendObjects.u_year;
						// 人员岗位
                        gridObj.u_position_EXName = _data[i].extendObjects.position_name
                        gridObj.u_position = _data[i].extendObjects.position_phid
						// 人员费率
						gridObj.u_personnel_rate = _data[i].extendObjects.u_personnel_rate;
						// 人工费合计
						gridObj.u_labor_amt_ori = _data[i].extendObjects.u_labor_amt;
						gridObj.u_labor_amt = _data[i].extendObjects.u_labor_amt;
						// 数量
						gridObj.u_qty = _data[i].extendObjects.u_qty;
						gridObj.u_qty_ori = _data[i].extendObjects.u_qty;
						// 1- 12 月
						for (let j = 1; j <= 12; j++) {
							const _str = `u_man_days_${j < 10 ? '0' + j : j}`
							const _str_ori = `u_man_days_${j < 10 ? '0' + j : j}_ori`
							gridObj[_str] = _data[i].extendObjects[_str];
							gridObj[_str_ori] = _data[i].extendObjects[_str];
						}
						gridArr.push(gridObj);
					}
					//调用新增表体行数据的函数
					let _count = 0;
					gridArr.forEach(item => {
						_count += item.u_svc_labor_amt_ori
					})
					$NG.updateState((updater) => {
						_countMaps.d1 = _count
						updater.data.p_form_dev_cost_budget_chg.setProps({
							u_total_labor_amt_ori: _count,
						})
					})
					dgrid1.addRows(gridArr);
				})
			}
			if (dgrid2) {
				$NG.execServer('getDevDaliyBudgetInfo', {
					cnt: mstform.getItem('u_cnt').getValue()
				}, function (res) {
					let _data = null
					if (typeof res.data === 'string') {
						_data = JSON.parse(res.data)
					} else {
						_data = res.data
					}
					console.log(`测试测试日常`, _data);
					//默认增行,批量新增表体数据
					var gridArr = []; //定义表体数组
					var gridCount = res.count; //增加的行数,可根据从数据库从取出的数据总数增行
					for (var i = 0; i < gridCount; i++) {
						//对表体字段进行赋值,可以取数据库中的值进行赋值
						var gridObj = {
						};
						gridObj.u_source_phid = _data[i].extendObjects.phid
						gridObj.u_year = _data[i].extendObjects.u_year;
						gridObj.u_dev_daliy_amt = _data[i].extendObjects.u_dev_daliy_amt;
						gridObj.u_dev_daliy_amt_ori = _data[i].extendObjects.u_dev_daliy_amt;
						gridObj.u_expense_code = _data[i].extendObjects.u_expense_code;
						gridObj.u_expense_name = _data[i].extendObjects.u_expense_name;
						gridObj.u_expense_description = _data[i].extendObjects.u_expense_description
						// 1- 12 月
						for (let j = 1; j <= 12; j++) {
							const _str = `u_expenses_${j < 10 ? '0' + j : j}`
							const _str_ori = `u_expenses_${j < 10 ? '0' + j : j}_ori`
							gridObj[_str] = _data[i].extendObjects[_str];
							gridObj[_str_ori] = _data[i].extendObjects[_str];
						}
						gridArr.push(gridObj);
					}
					let _count = 0;
					gridArr.forEach(item => {
						_count += item.u_annual_svc_amt
					})
					$NG.updateState((updater) => {
						_countMaps.d2 = _count
						updater.data.p_form_dev_cost_budget_chg.setProps({
							u_total_daily_amt_ori: _count
						})
					})
					//调用新增表体行数据的函数
					dgrid2.addRows(gridArr);
					dgrid2.refreshView()
				})
			}
		}, 200)
	}, "p_form_dev_cost_budget_chg.u_cnt");
     // 获取项目信息
     function getPtInfoByPhid() {
		if (mstform.getItem("phid_pc").getValue()) {
			$NG.execServer(
				"getPtInfoByPhid",
				{ phid: mstform.getItem("phid_pc").getValue() },
				function (res) {
					const datas = JSON.parse(res.data)[0].extendObjects;
					console.log(`获取项目信息`,datas);
					//帮助字段赋值
					$NG.updateState((updater) => {
						updater.data.p_form_dev_cost_budget_chg.setProps({
							u_pc_no: datas.pc_no, //项目编码
							//项目类型
							u_pc_type:{
								label:datas.type_name,
								value:datas.type_phid
							},
							u_sqgw: {
								//售前顾问
								value: datas.user_sqgw_phid,
								label: datas.user_sqgw_name,
							},
							u_division: {
								//事业部or组织
								value: datas.phid_org_phid,
								label: datas.phid_org_name,
							},
							u_regional_center: {
								//区域中心
								value: datas.regional_center_phid,
								label: datas.regional_center_name,
							},
                            u_dept: {
                                //部门
                                value: datas.dept_phid,
                                label: datas.dept_name,
                            },
                            u_region:{
                                //部门
                                value: datas.dept_phid,
                                label: datas.dept_name,
                            },
							u_product_line: {
								//产品线
								value: datas.midwife_phid,
								label: datas.midwife_name,
							},
						});
					});
				}
			);
		}
	}

    // 获取合同信息
	function getCntInfo(){
        $NG.execServer(
            "getCntMInfoByPhid",
            { phid: mstform.getItem("u_cnt").getValue() },
            function (res) {
                const datas = JSON.parse(res.data)[0].extendObjects;
                console.log(`合同：`,datas);
                //帮助字段赋值
                $NG.updateState((updater) => {
                    updater.data.p_form_dev_cost_budget_chg.setProps({
                        u_agreed_sts_dt: datas.start_dt, //计划完工日期
                        u_agreed_pcl_dt: datas.end_dt, //计划竣工日期
                        u_cnt_no:datas.pcm_no,
                        u_invoice_type:{
                            label:datas.invoice_type_name,
                            value:datas.invoice_type_phid
                        }
                    });
                });
            }
        );
    }

    // 过滤合同
    function cntMFilter() {
		if (!mstform.getItem("phid_pc").getValue()) {
			return;
		}
        console.log(`开始过滤`);
		$NG.updateUI((updater, state) => {
			updater.fieldSetForm.p_form_dev_cost_budget_chg.u_cnt.setProps({
				onBeforeOpen: async () => {
					var phid_pc = $NG
						.getCmpApi("p_form_dev_cost_budget_chg")
						.getItem("phid_pc")
						.getValue();
					if (!phid_pc) {
						$NG.alert("请先选择项目");
						return false;
					} else {
						return true;
					}
				},
				...(!!$NG
					.getCmpApi("p_form_dev_cost_budget_chg")
					.getItem("phid_pc")
					.getValue() && {
					clientSqlFilter: {
						bill_type: 1,
						phid_pc: $NG
							.getCmpApi("p_form_dev_cost_budget_chg")
							.getItem("phid_pc")
							.getValue(),
					},
				}),
			});
		});
	}

    // 汇总明细数据到主表
    function sum(){
        const _rowD = dgrid1.getRows()
        const _rowD2 = dgrid2.getRows()
        let _countD1 = 0
        let _countD2 = 0
        _rowD.forEach(item =>{
            _countD1 += Number(item.u_labor_amt) || 0
        })
        _rowD2.forEach(item =>{
            _countD2 += Number(item.u_dev_daliy_amt) || 0
        })
        $NG.updateState((updater)=>{
            updater.data.p_form_dev_cost_budget_chg.setProps({
                u_total_labor_amt: _countD1,
                u_total_daily_amt: _countD2,
                u_total_dev_amt: _countD1 + _countD2
            })
        })
    }
});